package com.idp.web.security.handle;

import com.alibaba.fastjson2.JSON;
import com.idp.common.model.LoginInfo;
import com.idp.common.model.ResultModel;
import com.idp.common.token.service.TokenService;
import com.idp.system.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出登录处理类
 * @author king
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private LoginService loginService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 删除用户缓存记录
        LoginInfo loginInfo = tokenService.removeToken();

        if(loginInfo != null) {
            // 清空菜单权限缓存
            loginService.deleteRuleMenusCache(loginInfo.getId());
            // 清空按钮权限缓存
            loginService.deleteRuleButtonsCache(loginInfo.getId());
        }

        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(JSON.toJSONString(ResultModel.success("退出成功", null)));
    }
}
